import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store/index'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '@/utils/auth'

import { asyncRoutes } from './router'

NProgress.configure({ showSpinner: false })

Vue.use(VueRouter)


function hasPermission(roles, permissionRoles) {
  if (roles.indexOf('admin') >= 0) return true // admin permission passed directly
  if (!permissionRoles) return true
  return roles.some(role => permissionRoles.indexOf(role) >= 0)
}

let routes = [
  {
    path: '/',
    redirect: '/test/cityList'
  },
  {
    path: '/login',
    component: () => import('../pages/login/index.vue'),
    meta: {

    }
  },
  {
    path: '/401',
    component: () => import('../pages/404/index.vue'),
    meta: {

    }
  },
  {
    path: '/*',
    component: () => import('../pages/404/index.vue'),
    meta: {

    }
  }
]

routes = asyncRoutes.concat(routes)
let router = new VueRouter({
  routes
})


router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({
        path: '/'
      })
      NProgress.done() 
    } else {
      if (hasPermission(store.getters.roles, to.meta.roles)) {
        next() 
      } else {
        next({
          path: '/401',
          replace: true,
          query: {
            noGoBack: true
          }
        })
      }
    }
  } else if (to.path === '/login') {
    next()
  } else {   
    next('/login')
    NProgress.done()
  }
})

router.afterEach((to, from) => {
  store.commit('SET_TAGLIST', {
    url : to.fullPath,
    name:to.meta.title
  })
  NProgress.done() 
})
export default router